<template>
  <view class="page-container">
    <view class="form">
      <view class="form-item">
        <input type="text" placeholder="主题" v-model="topic" />
      </view>
      <view class="form-item">
        <textarea placeholder="内容" v-model="content"></textarea>
      </view>
      <button @tap="publish">发布</button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      topic: '',
      content: '',
	   userInfo: {}
    };
  },
  onLoad() {
    const app = getApp();
    if (app.globalData.userInfo) {
      this.userId = app.globalData.userInfo.id;
      this.userInfo = app.globalData.userInfo;
	  this.user = app.globalData.userInfo.user;
    } else {
      uni.showToast({
        title: '用户未登录或信息未加载',
        icon: 'none'
      });
      uni.relaunch({
        url: '/pages/login/login' // 重定向到登录页面
      });
    }
  },
  methods: {
    publish() {
      // 构建发布请求的URL
      const publishUrl = `http://127.0.0.1:8081/inserttopic/?topic=${encodeURIComponent(this.topic)}&content=${encodeURIComponent(this.content)}&author=${encodeURIComponent(this.user)}&authorid=${encodeURIComponent(this.userId)}`;
      uni.request({
        url: publishUrl,
        method: 'GET',
        success: (res) => {
          if (res.statusCode === 200) {
            uni.showToast({
              title: '发布成功',
              icon: 'success'
            });
            // 清空表单
            this.topic = '';
            this.content = '';
            this.author = '';
            this.authorId = '';
          } else {
            uni.showToast({
              title: '发布失败',
              icon: 'none'
            });
          }
        },
        fail: (error) => {
          console.error('请求失败:', error);
          uni.showToast({
            title: '请求失败',
            icon: 'none'
          });
        }
      });
    }
  }
};
</script>

<style>
.page-container {
  background-color: #eee;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.form {
  width: 90%;
}

.form-item {
  margin-bottom: 20rpx;
}

input, textarea {
  border: 1px solid #ccc;
  border-radius: 4px;
  padding: 10rpx;
  width: 100%;
}

button {
  background-color: #1AAD19;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 10rpx;
  width: 100%;
  margin-top: 20rpx;
}
</style>